﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using T_Person.BaseRep;
using T_Person.BaseRep.Impls;
using T_Person.BaseRep.Interface;

namespace T_Person.APi.Expention
{
    public static class SerContext
    {
        public static IServiceCollection AddService(this IServiceCollection services)
        {
            services.AddTransient(typeof(IBaseRepInterface<>), typeof(BaseWays<>));
            services.AddScoped<IEmployeeRep, EmployeeRepways>();
            services.AddScoped<IPersonnelRep, PersonnelRepways>();
            return services;
        }
        public static IServiceCollection AddDbcontextService<T>(this IServiceCollection services, string? con, bool enableSqlLog) where T : DbContext
        {
            return services.AddDbContext<T>(m =>
            {
                m.UseSqlServer(con, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    m.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure.AddFilter((n, level) => n == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
                    }));
                }
            });
        }
        public static void AddJwt(this IServiceCollection services, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(x =>
                {
                    var secretByete = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                    x.TokenValidationParameters = new TokenValidationParameters()
                    {
                        //验证发布者
                        ValidateIssuer = true,
                        ValidIssuer = builder.Configuration["Authentication:Issuer"],
                        //验证验收者
                        ValidateAudience = true,
                        ValidAudience = builder.Configuration["Authentication:Audience"],
                        //验证是否过期
                        ValidateLifetime = true,
                        //验证私钥
                        IssuerSigningKey = new SymmetricSecurityKey(secretByete)
                    };
                });
        }
    }
}
